const https = require('https');

const { formatTime } = require('./util')

const SQLHelper = require('./SQLHelper')
//雪花算法生成id
const snowflake = require('./snowflake');

const multer = require('multer')
const storage = multer.diskStorage({
  destination: './uploads',
  filename: function (req, file, cb) {
    ///获取图片类型
    let fileType = file.originalname.split('.')
    fileType = fileType[fileType.length - 1]
    cb(null, snowflake() + '.' + fileType)
  }
})
const upload = multer({ storage: storage })


module.exports = function (app) {
  ///登录拦截中间件
  function loginRouter (req, res, next) {
    if (req.method == 'OPTIONS') {
      next()
      return;
    }
    let token = req.headers.token
    if (token) {
      SQLHelper(`select * from session where id = ${token} and state = 1`).then(ret => {
        if (ret.length) {
          let session = ret[0]
          ///2H
          if (new Date().getTime() - session.createTime < 2 * 60 * 60 * 1000) {
            req.session = {
              userId: session.userId,
              userName: session.userName
            }
            next()
          } else {
            res.status(400).send({ errorMsg: '登录超时' })
          }
        } else {
          res.status(400).send({ errorMsg: '当前用户未登录' })
        }
      })
    } else {
      res.status(400).send({ errorMsg: '缺少token，请先进行登录' })
    }
  }

  ///让初登录以外的所有小程序接口都需要进行先验证登录
  app.use('/admin', loginRouter)

  ///文件上传
  app.post('/upload', upload.single('file'), (req, res) => {
    res.send(req.file)
  })

  //管理后台登录
  app.post('/login', (req, res) => {
    let userName = req.body.userName
    let passWord = req.body.passWord
    if (userName && passWord) {
      SQLHelper(`
            select * from user where userName = '${userName}'
        `).then(users => {
        if (users.length) {///正常登陆
          let user = users[0]
          if (passWord == user.passWord) {
            let token = snowflake()
            //缓存到token到session表    
            SQLHelper(`
                INSERT INTO session(id,userId,userName,inTime,createTime,platform)
                VALUES(${token},'${user._id}','${user.nickName}','${formatTime(new Date())}',${new Date().getTime()},'admin')
                `).then(ret => {
              res.send({
                code:200,
                nickName: user.userName,
                token,
                avatarUrl: user.photo,
                _id: user._id
              })
            })
          } else {
            res.send({ errorMsg: '密码错误' })
          }
        } else {
          res.send({ errorMsg: '当前用户不存在' })
        }
      })
    } else {
      res.send({ errorMsg: '用户名和密码不能为空' })
    }
  })
  // 注册
  app.post('/regist', (req, res) => {
    let {registName,registEmil,registPassword} =  req.body
    // console.log(registName,registEmil,registPassword);
    if (registName && registPassword) {
      SQLHelper(`INSERT INTO user(userName,passWord,emil) 
      VALUES('${registName}','${registPassword}','${registEmil}')
      `).then(ret => {
        res.send({
          code:200,
          message:'注册成功'
        })
      })
    }else {
      res.send({ errorMsg: '注册失败' })
    }
  })

  /**
   * 接口
   * 
   **/
  

}

